import socket


def server_client(new_socket):
    '''为这个客户端返回数据'''
    # 1.接受浏览器发过来请求
    # GET / HTTP / 1.1
    request = new_socket.recv(1024)
    print(request)

    # 返回http格式的数据
    # 准备发给浏览器的数据 -- header

    response = 'HTTP/1.1 200 OK'
    response += '\r\n'  # \r\n 表示换行

    # 准备发给浏览器的数据 -- body
    response += 'hahaha'
    new_socket.send(response.encode('utf-8'))

    # 为客户端服务
    new_socket.close()


def main():
    # 创建套接字
    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # 绑定
    tcp_server_socket.bind(('192.168.61.1', 8888))

    # 监听套接字
    tcp_server_socket.listen(128)
    while True:
        # 等待客户端链接
        new_socket, client_address = tcp_server_socket.accept()

        # 为客户端服务
        server_client(new_socket)

    # 关闭套接字
    tcp_server_socket.close()


if __name__ == "__main__":
    main()
